from invidious import Video as RVideo

from src.utils import *

import time
import os

class Video(RVideo):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        try:
            self.url          = kwargs['url']
            self.watched_time = kwargs['watched_time']
            self.isWatched    = kwargs['isWatched']
        except:
            self.url = ""
            self.watched_time = 0
            self.isWatched = False

    def to_json(self):
        return self.to_history_dict(current_timestamp=False)

    def to_history_dict(self, current_timestamp=True):
        if not hasattr(self, "watched_time"): self.watched_time = 0
        hdict = self.__dict__
        hdict['type'] = 'video'

        if current_timestamp: hdict['published'] = time.time()

        print(hdict)

        return hdict

    def from_history_dict(self, hdict):
        self.title          = hdict['title']
        self.videoId        = hdict['videoId']
        self.lengthSeconds  = hdict['lengthSeconds']
        self.author         = hdict['author']
        self.published      = hdict['published']
        
        if 'watched_time' in hdict: self.watched_time = hdict['watched_time']

        return self

    def in_history(self, history):
        for hvideo in history.video_list:
            if hasattr(hvideo, 'videoId') and self.videoId == hvideo.videoId: 
                self.watched_time = hvideo.watched_time
                return True
        return False

    def from_history(self, history):
        for hvideo in history.video_list:
            if self.videoId == hvideo.videoId:
                return hvideo
        return None

    def download(self) -> (str | None):
        try: 
            os.system(f'yt-dlp {self.url} --output {self.title}.webm')
            return self.title+".webm"
        except:
            print("ERROR: yt-dlp not found")
            return None


